import winston from 'winston';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';

const { combine, timestamp, printf, colorize, json } = winston.format;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 自定义日志格式
const logFormat = printf(({ level, message, timestamp, stack }) => {
  return `${timestamp} ${level}: ${stack || message}`;
});

// 开发环境日志配置
const devLogger = () => {
  return winston.createLogger({
    level: process.env.LOG_LEVEL || 'info',
    format: combine(
      colorize(),
      timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
      winston.format.errors({ stack: true }),
      logFormat
    ),
    transports: [new winston.transports.Console()],
  });
};

// 生产环境日志配置
const prodLogger = () => {
  return winston.createLogger({
    level: 'info',
    format: combine(timestamp(), winston.format.errors({ stack: true }), json()),
    defaultMeta: { service: 'student-course-selection-system' },
    transports: [
      new winston.transports.File({
        filename: path.join(__dirname, '../../logs/error.log'),
        level: 'error',
      }),
      new winston.transports.File({
        filename: path.join(__dirname, '../../logs/combined.log'),
      }),
    ],
  });
};

// 根据环境选择日志配置
const logger = process.env.NODE_ENV === 'production' ? prodLogger() : devLogger();

// 确保日志目录存在
if (process.env.NODE_ENV === 'production') {
  const logDir = path.join(__dirname, '../../logs');
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir);
  }
}

export default logger;
